package com.ruijie.acl.importdevice.service;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.ruijie.acl.service.AclDeviceService;
import com.ruijie.emp.asynchandle.AbstractAsyncHandleService;
import com.ruijie.emp.asynchandle.AsyncHandleType;
import com.ruijie.emp.device.Device;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.service.Repository;

/**
 * <p>
 * Title: 处理PE调用异步逻辑
 * </p>
 * <p>
 * Description: handle用来处理service，处理调用异步逻辑
 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: Ruijie Co., Ltd.
 * </p>
 * <p>
 * Create Time: 2009-07-14
 * </p>
 * <p>
 * Update Time:
 * </p>
 * <p>
 * Updater:
 * </p>
 * <p>
 * Update Comments:
 * </p>
 *@author ASAI
 */
public class ImportDeviceAsyncHandleService extends AbstractAsyncHandleService<Device>{

	@SuppressWarnings("unchecked")
	private Repository deviceService;
	private ImportAsyncServiceParameter parameter;


	@SuppressWarnings("unchecked")
	public Repository getDeviceService() {
		return deviceService;
	}

	@SuppressWarnings("unchecked")
	public void setDeviceService(Repository deviceService) {
		this.deviceService = deviceService;
	}


	public ImportAsyncServiceParameter getParameter() {
		return parameter;
	}

	public void setParameter(ImportAsyncServiceParameter parameter) {
		this.parameter = parameter;
	}

	@Override
	protected boolean asyncHandleInstance(Object object) {
		parameter = (ImportAsyncServiceParameter)object;
		List<Device> devices = queryDeviceByIds(parameter.getDeviceIds());
		setTotal(devices.size());
		
		for(Device device :devices){
			executeThreadTask(device);
		}
	    //executeThreadPool(1, 1, 0, false, devices);
		return true;
	}

	@Override
	protected boolean bizMutexValidate(Object object) {
		return true;
	}

	@Override
	protected void destroyInstance(Object object) {
	}

	@Override
	protected AsyncHandleType getAsyncHandleType() {
		return AsyncHandleType.ACLImport;
	}

	@Override
	protected void initialize(Object object) {
	}

	@Override
	protected void executeThreadTask(Object object) {
		
		if (isStopped())
            return;
        Device device = (Device) object;
        // 开始导入设备
		addLogger("device_import_message_startimport", device.getName(), device.getIp());
        try {
            this.refresh(device); // 设备可能被删除了
        } catch (Exception e) {
            logger.error(e);
            addLogger("device_import_message_failure_forlost", device.getName(), device.getIp());
            countOfFaulureIncrement();
            return;
        }
        try {
        	BusinessException businessException = null;
        	businessException = ((AclDeviceService)deviceService).loadInfo(device);
        	if (businessException != null){
        		if (businessException.getMessage() == null){
        			throw new Exception();
        		}else{
        			throw businessException;
        		}
        	}
			//设备导入成功。
			addLogger("device_import_message_endimport_success", device.getName(), device.getIp());
			countOfSuccessIncrement();
        }catch (BusinessException bex){
        	logger.error(bex);
        	//设备导入失败。失败原因
        	if (bex.getMessage().equals("device_import_message_ascode_diff")){
        		addLogger("device_import_message_ascode_diff", device.getName(), device.getIp());
        	}else{
        		addLogger("device_import_message_endimport_failure", device.getName(), device.getIp() , bex.populate(this.getMessageSource()));
        	}
        	countOfFaulureIncrement();
        }catch (Exception ex){  
        	logger.error(ex);
        	//设备导入失败。失败原因
        	if (ex == null || ex.getMessage() == null || ex.getMessage().equals("")){
        		addLogger("device_import_message_endimport_failure_simple", device.getName(), device.getIp());
        	}else{
        		addLogger("device_import_message_endimport_failure", device.getName(), device.getIp() , ex.getMessage());
        	}
        	countOfFaulureIncrement();
        }
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void fillCache(Object... values) {
		List<Device> devices = (List<Device>) values[0];
        for (Device value : devices) {
            if (isStopped())
                break;
            addCache(value);
        }
	}
	
	/**
	 * 根据ID取得设备
	 * @param ids 设备ID
	 * @return 设备实体列表
	 */
	@SuppressWarnings("unchecked")
	private List<Device> queryDeviceByIds(Long[] ids){
		Criteria criteria = createCriteria(Device.class);
		criteria.add(Restrictions.in("id", ids));
		return (List<Device>)criteria.list();
	}
}
